package com.chukun.spring.configuration.metadata;

import com.chunkun.ioc.domain.User;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.util.ObjectUtils;

/**
 * @author chukun
 *   bean的配置元信息示例
 */
public class BeanConfigurationMetaDataDemo {

    public static void main(String[] args) {

        // 生成 user 的 BeanDefinitionBuilder
        BeanDefinitionBuilder definitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(User.class);
        // 获取beanDefinition
        AbstractBeanDefinition beanDefinition = definitionBuilder.getBeanDefinition();
        //设置上下文信息（不会影响初始化） ---> name --> chukun
        beanDefinition.setAttribute("name","chukun");
        //bean 添加属性
        definitionBuilder.addPropertyValue("name","chukun001");

        // 添加source
        beanDefinition.setSource(BeanConfigurationMetaDataDemo.class);

        // 初始化默认的 beanFactory
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();

        // 加后置处理器，定制化处理
        beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
                if (ObjectUtils.nullSafeEquals("user",beanName) && bean instanceof User){
                    User user = (User) bean;
                    BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
                    Object source = definition.getSource();
                    String name = null;
                    if (BeanConfigurationMetaDataDemo.class.equals(source)) {
                        name = "source-"+user.getName();
                    } else {
                        name = (String) definition.getAttribute("name");
                    }
                    user.setName(name);
                }
                return bean;
            }
        });

        // 注册bean的相关信息
        beanFactory.registerBeanDefinition("user",beanDefinition);
        // 依赖查找
        User bean = beanFactory.getBean("user",User.class);
        /**
         * 不加处理器的输出 : User{id=null, name='chukun001'}
         *
         * 1.加了后置处理器，就会变成 User{id=null, name='chukun'}
         * 2. source 输出 User{id=null, name='source-chukun001'}
         */
        System.out.println(bean);

    }
}
